package com.dd.cloud.user.service.phar.pharservice;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dd.cloud.common.constants.PharConstants;
import com.dd.cloud.common.constants.PresConstants;
import com.dd.cloud.common.constants.RedisKeyConstants;
import com.dd.cloud.common.enums.ZkExceptionEnum;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.common.utils.*;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.user.DTO.CallbackPresStatusReq;
import com.dd.cloud.user.DTO.CancelPresReq;
import com.dd.cloud.user.DTO.CommonParamReq;
import com.dd.cloud.user.DTO.hr.ReturnDrugList;
import com.dd.cloud.user.DTO.hr.SendPresBodyDTO;
import com.dd.cloud.user.DTO.hr.SendPresDrugsDTO;
import com.dd.cloud.user.DTO.yf.ReturnQueryDrugKlResultDTO;
import com.dd.cloud.user.DTO.yf.ReturnQueryPresStatusResultDTO;
import com.dd.cloud.user.DTO.yf.SendQueryDrugKlDTO;
import com.dd.cloud.user.DTO.yf.SendQueryPresStatusDTO;
import com.dd.cloud.user.entity.doctor.PatientMedCard;
import com.dd.cloud.user.entity.order.OrderPay;
import com.dd.cloud.user.entity.phar.Pharmacy;
import com.dd.cloud.user.entity.phar.PharmacyDocking;
import com.dd.cloud.user.entity.pres.*;
import com.dd.cloud.user.enums.ExceptionEnum;
import com.dd.cloud.user.req.pres.PresCreateHrReq;
import com.dd.cloud.user.req.pres.PresCreateReq;
import com.dd.cloud.user.req.pres.PresPatientAddrReq;
import com.dd.cloud.user.service.doctor.IDoctorDetailService;
import com.dd.cloud.user.service.doctor.IDoctorEquityService;
import com.dd.cloud.user.service.log.ILogErrorService;
import com.dd.cloud.user.service.order.IOrderPayService;
import com.dd.cloud.user.service.phar.IPharmacyDockingService;
import com.dd.cloud.user.service.phar.IPharmacyService;
import com.dd.cloud.user.service.pres.*;
import com.dd.cloud.user.service.sms.ISmsService;
import com.dd.cloud.user.util.PdfToImgUtil;
import com.dd.cloud.user.vo.HrResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.misc.Hash;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 康美药房服务类
 *
 * @author Lx
 * @version 1.0
 */
@Slf4j
@Service
public class HrPharService extends PharAbstractService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ILogErrorService logErrorService;
    @Autowired
    private IPresPrescriptionService presPrescriptionService;
    @Autowired
    private IPharmacyDockingService pharmacyDockingService;
    @Autowired
    private IPharmacyService pharmacyService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private IPresHrDetailService presHrDetailService;
    @Autowired
    private IOrderPayService orderPayService;
    @Autowired
    private IPresPretrialDrugsService presPretrialDrugsService;

    @Autowired
    private IDrugsModelService drugsModelService;

    @Autowired
    private IDoctorDetailService doctorDetailService;

    @Autowired
    private IPresHandleRecordService presHandleRecordService;

    @Autowired
    IPresHrPharRoamService presHrPharRoamService;

    @Autowired
    private ISmsService smsService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IDoctorEquityService doctorEquityService;


    /**
     * @return String token
     * @description 获取药房token
     * @author czg
     * @date 2023/6/2 16:34
     */
    public String getToken() {
        String token = redisTemplate.opsForValue().get(RedisKeyConstants.HR_TOKEN);
        if (StringUtils.isBlank(token)) {
            QueryWrapper<Pharmacy> qp = new QueryWrapper<>();
            qp.lambda().eq(Pharmacy::getFlag, PharConstants.Flag.HR);
            Pharmacy pharmacy = pharmacyService.getOne(qp);
            if (pharmacy == null) {
                logErrorService.presBackLog("药房不存在", "获取华润token", "pharmId=" + pharmacy.getId());
                return null;
            }
            QueryWrapper<PharmacyDocking> qd = new QueryWrapper<>();
            qd.lambda().eq(PharmacyDocking::getPharId, pharmacy.getId()).eq(PharmacyDocking::getStatus, PharConstants.DockingStatus.NOMER);
            PharmacyDocking pharmacyDocking = pharmacyDockingService.getOne(qd);
            if (pharmacyDocking == null) {
                logErrorService.presBackLog("药房接口信息不存在", "获取华润token", "pharmId=" + pharmacy.getId());
                return null;
            }
            Map<String, String> clMap = new HashMap<>();
            clMap.put("client_id", pharmacyDocking.getMchId());
            String body = JSON.toJSONString(clMap);
            String hash = Md5Utils.hash(body);
            String encrypt = RsaUtils.encrypt(hash, pharmacyDocking.getEncryptyKey());
            HttpHeaders head = new HttpHeaders();
            head.add("Content-Type", "text/plain");
            head.add("sign", encrypt);
            HttpEntity<String> entity = new HttpEntity<>(body, head);
            log.info("获取token:{}", JSON.toJSONString(entity));
            HrResponse<String> data = null;
            try {
                data = restTemplate.postForObject(pharmacyDocking.getGetTokenUrl(), entity, HrResponse.class);
                log.info("华润药房获取token返回:{}", data);
            } catch (Exception e) {
                log.info(e.getMessage());
                logErrorService.presBackLog("获取token失败", "获取token异常", "bodyDTO=" + JSON.toJSONString(data));
            }
            Map<String, String> map;
            if (data != null && data.getStatus().equals("200")) {
                map = JsonUtils.parseMap(JSON.toJSONString(data.getData()), String.class, String.class);
                if (map != null) {
                    String newToken = map.get("token");
                    redisTemplate.opsForValue().set(RedisKeyConstants.HR_TOKEN, newToken, 24L, TimeUnit.HOURS);
                    return newToken;
                }
            }
        }
        return token;
    }

    /**
     * 添加药房的处方详情
     *
     * @param req
     * @param medCard
     */
    @Override
    public void addPresDetail(PresCreateReq req, PatientMedCard medCard) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        PresCreateHrReq hrReq = (PresCreateHrReq) req;
        PresHrDetail detail = new PresHrDetail();
        BeanUtils.copyProperties(hrReq, detail);
        detail.setTencode(hrReq.getTencode());
        detail.setId(hrReq.getTencode());
        detail.setVisitNo(hrReq.getTencode().replace("CF", "MZ"));
        detail.setOrganName("广州阿康中医诊所有限公司");
        detail.setPrice(BigDecimalUtils.divide(req.getDiscountMoney() == null ? req.getMoney() : req.getDiscountMoney(), 100));
        detail.setDoctorName(loginInfo.getName());
        detail.setQuantity(hrReq.getAllDose());
        detail.setFrequency(hrReq.getDayDose());
        detail.setName(medCard.getName());
        detail.setAge(CalendarUtil.getAge(medCard.getBirthDate()));
        detail.setSex(Objects.equals(medCard.getSex(), "男") ? 1 : 2);
        detail.setDepartmentName(hrReq.getDepName());
        detail.setDiagnose(hrReq.getDiagnosticName());
        boolean i = presHrDetailService.saveOrUpdate(detail);
        if (!i) {
            throw new ZekeException(ExceptionEnum.PRES_CREATE_ERROR, "处方信息保存失败");
        }
    }

    @Override
    public boolean sendPresToPhar(OrderPay pay) {
        boolean succ = false;
        log.info("发送处方到华润三九药房");
        if (StringUtils.isBlank(pay.getServerNo())) {
            //没有处方编码 数据异常, 退款
            orderPayService.refund(pay.getOrderNo(), 0);
            logErrorService.presBackLog("没有处方编码-数据异常, 退款", "处方发送到华润三九药房异常", "tencode=" + pay.getServerNo());
            return succ;
        }
        PresPrescription presPrescription = presPrescriptionService.getById(pay.getServerNo());
        if (presPrescription == null) {
            //处方为空, 数据异常, 退款
            logErrorService.presBackLog("处方为空-数据异常", "处方发送到华润三九药房异常", "tencode=" + pay.getServerNo());
            return succ;
        }
        if (presPrescription.getStatus() == PresConstants.PresStatus.SENDPHARM) {
            //处方已发送到药房, 此为重复回调
            log.info("处方已发送到药房, 此为重复回调");
            return succ;
        }
        PresHrDetail hrDetail = presHrDetailService.getById(pay.getServerNo());
        if (hrDetail == null) {
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("获取发送给药房的详细数据失败", "处方发送到华润三九药房异常", "tencode=" + pay.getServerNo());
            return succ;
        }
        hrDetail.setOrderNo(pay.getOrderNo());
        Pharmacy pharmacy = pharmacyService.getById(presPrescription.getPharmId());
        if (pharmacy == null) {
            //药房为空, 数据异常 ,退款
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("药房为空-数据异常", "处方发送到华润三九药房异常", "tencode=" + pay.getServerNo());
            return succ;
        }
        QueryWrapper<PharmacyDocking> qd = new QueryWrapper<>();
        qd.lambda().eq(PharmacyDocking::getPharId, pharmacy.getId()).eq(PharmacyDocking::getStatus, PharConstants.DockingStatus.NOMER);
        PharmacyDocking pharmacyDocking = pharmacyDockingService.getOne(qd);
        if (pharmacyDocking == null) {
            //药房为空, 数据异常 ,退款
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("药房对接信息为空-数据异常", "处方发送到华润三九药房异常", "pharId=" + pharmacy.getId());
            return succ;
        }
        SendPresBodyDTO body = SendPresBodyDTO.detailToBodyDto(hrDetail);
        List<SendPresDrugsDTO> drugsDTOS = new ArrayList<>();
        QueryWrapper<PresPretrialDrugs> qw = new QueryWrapper<>();
        qw.lambda().eq(PresPretrialDrugs::getTencode, presPrescription.getTencode()).eq(PresPretrialDrugs::getStatus, PresConstants.PresDrugsStatus.NOMER);
        List<PresPretrialDrugs> drugsList = presPretrialDrugsService.list(qw);
        if (drugsList == null || drugsList.isEmpty()) {
            //没有处方药品, 数据异常, 退款
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("没有处方药品-数据异常", "处方发送到华润三九药房异常", "tencode=" + pay.getServerNo());
            return succ;
        }
        for (PresPretrialDrugs drugs : drugsList) {
            SendPresDrugsDTO drugsDTO = new SendPresDrugsDTO();
            drugsDTO.setNo(drugs.getId());
            drugsDTO.setDecoctWay(DataConvert(drugs.getDecocting()));
            drugsDTO.setGranule_id(drugs.getDrugnum());
            drugsDTO.setGranule_name(drugs.getHerbName());
            drugsDTO.setDose(BigDecimal.valueOf(drugs.getDrugallnum()));
            drugsDTOS.add(drugsDTO);
        }
        String imageBase64 = redisTemplate.opsForValue().get(RedisKeyConstants.PRES_IMG_BASE64_KEY + presPrescription.getTencode());
        if (StringUtils.isBlank(imageBase64)) {
            try {
                imageBase64 = PdfToImgUtil.getImagBase64(presPrescription.getPdfUrl());
                if (StringUtils.isBlank(imageBase64)) {
                    logErrorService.presBackLog("华润药房pdf转图片转BASE失败", "处理PDF转图片转BASE64", "orderNo=" + pay.getOrderNo());
                } else {
                    imageBase64 = "data:image/png;base64," + imageBase64;
                }
            } catch (Exception e) {
                log.info("图片生成BASE64失败");
                e.printStackTrace();
                logErrorService.presBackLog("华润药房pdf转图片转BASE失败", "处理PDF转图片转BASE64", "orderNo=" + pay.getOrderNo());
            }
        }
        log.info("处方图片BASE64:{}", imageBase64);
        body.setItems(drugsDTOS);
        body.setOrder_no(pay.getOrderNo());
        body.setId(presPrescription.getTencode());
        body.setVisit_no(hrDetail.getVisitNo());
        body.setName(hrDetail.getName());
        body.setAge(hrDetail.getAge() + "");
        body.setSex(hrDetail.getSex());
        body.setOrgan_name(hrDetail.getOrganName());
        body.setDepartment_name(StringUtils.isBlank(hrDetail.getDepartmentName()) ? "中医科" : hrDetail.getDepartmentName());
        body.setDoctor_name(hrDetail.getDoctorName());
        body.setDiagnose(presPrescription.getDiagnosticName());
        body.setQuantity(hrDetail.getQuantity());
        body.setConsignee(hrDetail.getConsigneeTel());
        body.setConsigneeTel(hrDetail.getConsigneeTel());
        body.setConsigneeAddr(hrDetail.getConsigneeAddr());
        body.setPrice(hrDetail.getPrice());
        body.setDescription(hrDetail.getDescription());
        body.setFrequency(hrDetail.getFrequency() + "");
        //发送处方单图
        body.setMd5Image(imageBase64);
        body.setProcesed(hrDetail.getProcesed());
        body.setTags(hrDetail.getTags() == null ? "" : hrDetail.getTags());
        String json = JSON.toJSONString(body);
        log.info("发送处方json数据:{}", json);
        String token = getToken();
        if (StringUtils.isBlank(token)) {
            logErrorService.presBackLog("药房获取颗粒药材信息接口错误信息，获取token不存在", "获取华润三九药材数据", "");
            return succ;
        }
        HrResponse<String> data;
        try {
            String hash = Md5Utils.hash(json);
            String encrypt = RsaUtils.encrypt(hash, pharmacyDocking.getEncryptyKey());
            HttpHeaders head = new HttpHeaders();
            head.add("Content-Type", "text/plain");
            head.add("sign", encrypt);
            head.add("token", token);
            HttpEntity<String> entity = new HttpEntity<>(json, head);
            log.info("请求参数:{}", JSON.toJSONString(entity));
            data = restTemplate.postForObject(pharmacyDocking.getServicesUrl(), entity, HrResponse.class);
            log.info("华润药房获取token返回:{}", data);
        } catch (Exception e) {
            log.info(e.getMessage());
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("请求参数数据加密失败", "处方发送华润三九制药药房异常", "bodyDTO=" + JSON.toJSONString(e.getMessage()));
            return succ;
        }
        String code = data.getStatus();
        log.info("发送处方返回数据:{}", JSON.toJSONString(data));
        if (!code.equals("200")) {
            logErrorService.presBackLog("药房下单接口返回异常信息", "处方发送华润三九制药药房异常", "res=" + data.getMsg());
            return succ;
        }
        log.info("发送处方成功----更新处方状态");
        PresPrescription update1 = new PresPrescription();
        update1.setTencode(pay.getServerNo());
        update1.setStatus(PresConstants.PresStatus.SENDPHARM);
        update1.setUpdateDate(LocalDateTime.now());
        boolean flag = presPrescriptionService.updateById(update1);
        if (!flag) {
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("发送处方到药房成功, 处方更新失败", "处方发送到华润三九制药异常", "jsonBody=" + presPrescription.toString());
            return succ;
        }
        PresHrDetail update2 = new PresHrDetail();
        update2.setTencode(pay.getServerNo());
        update2.setOrderNo(pay.getOrderNo());
        if (data != null) {
            String res = JSON.toJSONString(data.getData());
            log.info("返回的数据为:{}", res);
            JSONObject jsonObject = JSON.parseObject(res);
            String tcmOrderNo = (String) jsonObject.get("tcm_order_no");
            if (StringUtils.isNotBlank(tcmOrderNo)) {
                update2.setTcmOrderNo(tcmOrderNo);
            }
        }
        update2.setResult(JSON.toJSONString(data));
        flag = presHrDetailService.updateById(update2);
        if (!flag) {
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("发送处方到药房成功, 华润三九制药处方详情更新失败", "处方发送到华润三九制药制药药房异常", "jsonBody=" + presPrescription.toString());
            return succ;
        }
        //删除缓存中的图片
        redisTemplate.delete(RedisKeyConstants.PRES_IMG_BASE64_KEY + presPrescription.getTencode());
        return true;
    }

    private String convertData(String description) {
        if (StringUtils.isBlank(description)) {
            return "";
        }
        switch (description) {
            case "内服":
                return "neifu";
            case "外用":
                return "waiyong";
            default:
                return "";
        }
    }

    @Override
    public void cancelPres(CancelPresReq req) {
        log.info("华润三九药房无取消处方接口, 不支持取消处方");
        throw new ZekeException(ZkExceptionEnum.CANCEL_PRES_ERROR, "华润三九药房不支持线上取消处方,请联系管理员线下取消处方");
    }

    @Override
    public String presCallback(CallbackPresStatusReq req) {
        return "success";
    }

    @Override
    public String expressCallback(CommonParamReq req) {
        return "success";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePresPatientAddrInfo(PresPatientAddrReq req) {

    }

    public String DataConvert(String decocting) {
        if (StringUtils.isBlank(decocting)) {
            return "";
        }
        switch (decocting) {
            case "先煎":
                return "xianjian";
            case "后下":
                return "houxia";
            case "包煎":
                return "baojian";
            case "烊化":
                return "yanghua";
            case "打碎":
                return "dasui";
            case "另煎":
                return "lingjian";
            case "冲服":
                return "chongfu";
            default:
                return "";
        }
    }


    /**
     * 获取华润三九药材数据
     */
    public void pullHrDrug() {
        QueryWrapper<Pharmacy> qp = new QueryWrapper<>();
        qp.lambda().eq(Pharmacy::getFlag, PharConstants.Flag.HR);
        Pharmacy pharmacy = pharmacyService.getOne(qp);
        if (pharmacy == null) {
            logErrorService.presBackLog("药房不存在", "获取华润三九药房药材数据", "pharFlag=" + PharConstants.Flag.HR);
            return;
        }
        QueryWrapper<PharmacyDocking> qd = new QueryWrapper<>();
        qd.lambda().eq(PharmacyDocking::getPharId, pharmacy.getId()).eq(PharmacyDocking::getStatus, PharConstants.DockingStatus.NOMER);
        PharmacyDocking pharmacyDocking = pharmacyDockingService.getOne(qd);
        if (pharmacyDocking == null) {
            logErrorService.presBackLog("药房接口信息不存在", "获取华润三九药材数据", "pharId=" + pharmacy.getId());
            return;
        }

        Map<String, String> clMap = new HashMap<>();
        clMap.put("client_id", pharmacyDocking.getMchId());
        String body = JSON.toJSONString(clMap);
        String hash = Md5Utils.hash(body);
        String encrypt = RsaUtils.encrypt(hash, pharmacyDocking.getEncryptyKey());
        HttpHeaders head = new HttpHeaders();
        head.add("Content-Type", "text/plain");
        head.add("sign", encrypt);
        String token = getToken();
        if (StringUtils.isBlank(token)) {
            logErrorService.presBackLog("药房获取药材信息接口错误信息,token不存在", "获取华润三九药材数据", "");
            return;
        }
        head.add("token", token);
        HttpEntity<String> entity = new HttpEntity<>(body, head);
        log.info("请求数据:{}", entity);
        HrResponse<String> res = null;
        try {
            res = restTemplate.postForObject(pharmacyDocking.getGetKlDrugUrl(), entity, HrResponse.class);
        } catch (RestClientException e) {
            e.printStackTrace();
            logErrorService.presBackLog("药房获取颗粒药材信息接口错误信息", "获取华润三九药材数据", "message=" + res.getMsg());
            return;
        }
        log.info("-------获取药材结果-----result:{}", res);
        if (res.getStatus().equals("200")) {
            log.info("=====进入药材获取====");
            List<ReturnDrugList> resultDTOList = JSON.parseArray(JSON.toJSONString(res.getData()), ReturnDrugList.class);
            if (CollectionUtil.isEmpty(resultDTOList)) {
                logErrorService.presBackLog("药房获取药材信息接口无数据返回", "获取华润三九药材数据", "res=" + res);
                return;
            }
            drugsModelService.syncHrDrugInfo(resultDTOList, pharmacy.getId());
        } else {
            logErrorService.presBackLog("药房获取药材信息接口返回异常信息", "获取华润三九药材数据", "res=" + res);
        }
    }

    /**
     * 处理华润三九制药状态流转
     */
    public void presStatusRoamHr() {
        List<String> thirdIds = presHrDetailService.queryPresStatusRoamThirdPartyIdListHr();
        if (CollectionUtil.isEmpty(thirdIds)) {
            log.info("~~处理华润三九制药状态流转,暂无药房订单号处理~~");
//            logErrorService.presBackLog("暂无药房订单号处理", "处理华润三九制药状态流转", "pharFlag=" + PharConstants.Flag.HR);
            return;
        }
        QueryWrapper<Pharmacy> qp = new QueryWrapper<>();
        qp.lambda().eq(Pharmacy::getFlag, PharConstants.Flag.HR);
        Pharmacy pharmacy = pharmacyService.getOne(qp);
        if (pharmacy == null) {
            logErrorService.presBackLog("药房不存在", "处理华润三九制药状态流转", "pharFlag=" + PharConstants.Flag.HR);
            return;
        }
        QueryWrapper<PharmacyDocking> qd = new QueryWrapper<>();
        qd.lambda().eq(PharmacyDocking::getPharId, pharmacy.getId()).eq(PharmacyDocking::getStatus, PharConstants.DockingStatus.NOMER);
        PharmacyDocking pharmacyDocking = pharmacyDockingService.getOne(qd);
        if (pharmacyDocking == null) {
            logErrorService.presBackLog("药房接口信息不存在", "处理一方制药状态流转", "pharId=" + pharmacy.getId());
            return;
        }
        List<PresPrescription> updateListById = new ArrayList<>(thirdIds.size());
        List<PresHrPharRoam> saveList = new ArrayList<>(thirdIds.size());
        for (String item : thirdIds) {
            if (StringUtils.isBlank(item)) {
                continue;
            }
            String[] splits = item.split(",");
            int status;
            String tcmOrderNo = "";
            try {
                status = Integer.parseInt(splits[2]);
                tcmOrderNo = splits[0];
                log.info("华软处方状态,{},药房订单号:{}", status, tcmOrderNo);
            } catch (NumberFormatException e) {
                logErrorService.presBackLog("String转Integer错误", "处理一方制药状态流转", "res=" + Arrays.toString(splits));
                continue;
            }
            if (StringUtils.isBlank(tcmOrderNo)) {
                logErrorService.presBackLog("订单编号为空", "处理一方制药状态流转", "res=" + Arrays.toString(splits));
                continue;
            }
            String body = "{\"Tcm_order_no\":\"" + tcmOrderNo + "\"}";
            String hash = Md5Utils.hash(body);
            String encrypt = RsaUtils.encrypt(hash, pharmacyDocking.getEncryptyKey());
            HttpHeaders head = new HttpHeaders();
            head.add("Content-Type", "text/plain");
            head.add("sign", encrypt);
            String token = getToken();
            if (StringUtils.isBlank(token)) {
                logErrorService.presBackLog("获取华润三九药房token不存在", "获取华润三九药材token", "");
                return;
            }
            head.add("token", token);
            HttpEntity<String> entity = new HttpEntity<>(body, head);
            log.info("请求数据:{}", entity);
            HrResponse<String> res;
            try {
                res = restTemplate.postForObject(pharmacyDocking.getPreStatusUrl(), entity, HrResponse.class);
            } catch (RestClientException e) {
                e.printStackTrace();
                logErrorService.presBackLog("药房查询处方状态流转接口错误信息", "处理华润三九状态流转", "message=" + e.getMessage());
                continue;
            }

            log.info("查询华润三九状态结果:{}", JSON.toJSONString(res));
            JSONObject jsonObj = JSON.parseObject(JSON.toJSONString(res.getData()));
            if (jsonObj == null) {
                logErrorService.presBackLog("药房查询处方状态流转接无数据返回", "处理华润三九状态流转", "res=" + res);
                continue;
            }
            if (!res.getStatus().equals("200")) {
                logErrorService.presBackLog("药房查询处方状态流转接返回异常信息", "处理华润三九状态流转", "res=" + res);
                continue;
            }
            tcmOrderNo = (String) jsonObj.get("tcm_order_no");
            String tencode = (String) jsonObj.get("id");
            log.info("华润状态流转返回处方单号:{}", tencode);
            String pharStatus = (String) jsonObj.get("status");
            if (StringUtils.isBlank(pharStatus)) {
                logErrorService.presBackLog("华润药房返回状态异常", "处理华润三九状态流转", "tencode=" + tencode);
                continue;
            }
            PresPrescription update = new PresPrescription();
            String reason = "";
            reason = (String) jsonObj.get("preCheckFailCause");
            switch (pharStatus) {
                case "thz":
                    if (status != PresConstants.PresStatus.AUDITNO) {
                        update.setStatus(PresConstants.PresStatus.AUDITNO);
                        reason = (String) jsonObj.get("preCheckFailCause");
                        log.info("审核失败原因:{},处方号:{}", reason, tencode);
                    }
                    break;
                case "dsh":
                    if (status != PresConstants.PresStatus.AUDIT) {
                        update.setStatus(PresConstants.PresStatus.AUDIT);
                    }
                    break;
                case "pyz":
                    if (status != PresConstants.PresStatus.ADJUST) {
                        update.setStatus(PresConstants.PresStatus.ADJUST);
                    }
                    break;
                case "jzz":
                case "jyj":
                    if (status != PresConstants.PresStatus.TISANES) {
                        update.setStatus(PresConstants.PresStatus.TISANES);
                    }
                    break;
                case "yjc":
                    if (status != PresConstants.PresStatus.DELIVERY) {
                        Integer type = (Integer) jsonObj.get("expressCompany");
                        String expNo = (String) jsonObj.get("expNo");
                        log.info("快递公司类型:{},快递单号", type, expNo);
                        String expressCompany = "";
                        if (type != null && type == 1 && StringUtils.isNotBlank(expNo)) {
                            expressCompany = "顺丰";
                        }
                        update.setExpresscompany(expressCompany);
                        update.setExpressno(expNo);
                        update.setStatus(PresConstants.PresStatus.DELIVERY);
                        PresPrescription presPrescription = presPrescriptionService.getById(splits[1]);
                        if (StringUtils.isNotBlank(expressCompany) && StringUtils.isNotBlank(expNo)) {
                            smsService.sendDeliveryPres(presPrescription.getTencode(), presPrescription.getDoctorId(),
                                    presPrescription.getName(), expNo, expressCompany);
                        }
                        LambdaQueryWrapper<OrderPay> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(OrderPay::getServerNo, presPrescription.getTencode()).eq(OrderPay::getStatus, 2);
                        OrderPay orderPay = orderPayService.getOne(queryWrapper);
                        if (orderPay != null) {
                            doctorEquityService.saveDoctorEquity(orderPay, 2);
                        }
                    }
                    break;
                case "ywj":
                    if (status != PresConstants.PresStatus.SUC) {
                        update.setStatus(PresConstants.PresStatus.SUC);
                    }
                    break;
                case "ycz":
                    if (status != PresConstants.PresStatus.ERROR) {
                        update.setStatus(PresConstants.PresStatus.ERROR);
                    }
                    break;
                case "yfc":
                    if (status != PresConstants.PresStatus.CANCEL) {
                        update.setStatus(PresConstants.PresStatus.CANCEL);
                    }
                    break;
                default:
            }
            if (update.getStatus() != null) {
                update.setTencode(tencode);
                update.setUpdateDate(LocalDateTime.now());
                updateListById.add(update);
                PresHrPharRoam record = new PresHrPharRoam();
                record.setTencode(tencode);
                record.setStatus(update.getStatus());
                record.setTcmOrderNo(tcmOrderNo);
                record.setCreateDate(LocalDateTime.now());
                record.setResult(JSON.toJSONString(res));
                if (StringUtils.isNotBlank(reason)) {
                    record.setReason(reason);
                }
                saveList.add(record);
            }
        }
        if (CollectionUtil.isNotEmpty(updateListById)) {
            presPrescriptionService.updateBatchById(updateListById);
        }
        if (CollectionUtil.isNotEmpty(saveList)) {
            presHrPharRoamService.saveBatch(saveList);
        }
    }


    /**
     * PDF图片转BASE64 上传附件
     */
    public void upload(String orderNo) {
        OrderPay orderPay = orderPayService.getById(orderNo);
        if (orderPay == null) {
            return;
        }
        PresPrescription presPrescription = presPrescriptionService.getById(orderPay.getServerNo());
        if (presPrescription == null) {
            return;
        }
        if (StringUtils.isBlank(presPrescription.getPdfUrl())) {
            return;
        }
        QueryWrapper<Pharmacy> qp = new QueryWrapper<>();
        qp.lambda().eq(Pharmacy::getFlag, PharConstants.Flag.HR);
        Pharmacy pharmacy = pharmacyService.getOne(qp);
        if (pharmacy == null) {
            logErrorService.presBackLog("药房不存在", "上传处方图片", "pharFlag=" + PharConstants.Flag.HR);
            return;
        }
        QueryWrapper<PharmacyDocking> qd = new QueryWrapper<>();
        qd.lambda().eq(PharmacyDocking::getPharId, pharmacy.getId()).eq(PharmacyDocking::getStatus, PharConstants.DockingStatus.NOMER);
        PharmacyDocking pharmacyDocking = pharmacyDockingService.getOne(qd);
        if (pharmacyDocking == null) {
            logErrorService.presBackLog("药房接口信息不存在", "上传处方图片", "pharId=" + pharmacy.getId());
            return;
        }
        String imageBase64 = "";
        try {
            imageBase64 = PdfToImgUtil.getImagBase64(presPrescription.getPdfUrl());
            log.info("处方图片BASE64:{}", imageBase64);
        } catch (Exception e) {
            log.info("图片生成BASE64失败");
            e.printStackTrace();
            logErrorService.presBackLog("华润药房pdf转图片转BASE失败", "处理PDF转图片转BASE64", "orderNo=" + orderNo);
            return;
        }
        if (StringUtils.isBlank(imageBase64)) {
            logErrorService.presBackLog("华润药房pdf转图片转BASE失败", "处理PDF转图片转BASE64", "orderNo=" + orderNo);
            return;
        }
        String fix = "data:image/png;base64,";
        Map<String, String> map = new HashMap<>();
        map.put("imgType", "png");
        map.put("imgContent", "处方图");
        map.put("obtainEvidenceBase64", fix + imageBase64);
        map.put("orderNo", orderNo);
        String body = JSON.toJSONString(map);
        String hash = Md5Utils.hash(body);
        String encrypt = RsaUtils.encrypt(hash, pharmacyDocking.getEncryptyKey());
        HttpHeaders head = new HttpHeaders();
        head.add("Content-Type", "text/plain");
        head.add("sign", encrypt);
        String token = getToken();
        if (StringUtils.isBlank(token)) {
            logErrorService.presBackLog("获取华润三九药房token不存在", "上传处方图", "orderNo=" + orderNo);
            return;
        }
        head.add("token", token);
        HttpEntity<String> entity = new HttpEntity<>(body, head);
        log.info("请求数据:{}", entity);
        HrResponse<String> res;
        try {
            res = restTemplate.postForObject(pharmacyDocking.getUploadUrl(), entity, HrResponse.class);
        } catch (RestClientException e) {
            e.printStackTrace();
            logErrorService.presBackLog("上传处方图失败", "上传处方图", "message=" + e.getMessage());
            return;
        }
        log.info("查询华润三九状态结果:{}", JSON.toJSONString(res));
        if (!res.getStatus().equals("200")) {
            logErrorService.presBackLog("上传处方图失败", "上传处方图", "message=" + res.getMsg());
            return;
        }
        log.info("~~上传处方图成功~~orderNo=" + orderNo);
        JSONObject jsonObj = JSON.parseObject(JSON.toJSONString(res.getData()));
        String newFileId = (String) jsonObj.get("fileId");
        PresHrDetail presHrDetail = presHrDetailService.getById(orderPay.getServerNo());
        String oldFileId = presHrDetail.getFileId();
        log.info("上传的文件id:{},老的文件ids:{}", newFileId, oldFileId);
        if (StringUtils.isBlank(oldFileId)) {
            presHrDetail.setFileId(newFileId);
        } else {
            oldFileId = oldFileId + "," + newFileId;
            presHrDetail.setFileId(oldFileId);
        }
        presHrDetailService.updateById(presHrDetail);
    }
}
